package common

import (
	"context"
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"encoding/json"
	v1 "hotgo/api/api/common/v1"
	"hotgo/internal/library/storager"
	"hotgo/internal/model/input/apiin"
	"time"
)

func (c *ControllerV1) AliyunOssTokenMini(ctx context.Context, req *v1.AliyunOssTokenMiniReq) (res *v1.AliyunOssTokenMiniRes, err error) {

	res = new(v1.AliyunOssTokenMiniRes)
	config := storager.GetConfig()

	ossAppKey := config.OssSecretId
	ossSercret := config.OssSecretKey

	expiration := time.Now().Add(time.Minute * 30).Format("2006-01-02T15:04:05.000Z")

	policyMap := map[string]interface{}{
		"expiration": expiration,
		"conditions": []interface{}{
			[]interface{}{
				"content-length-range",
				0,
				1048576000,
			},
		},
	}

	jsonStr, err := json.Marshal(policyMap)
	if err != nil {
		return nil, err
	}
	policy := base64.StdEncoding.EncodeToString(jsonStr)
	mac := hmac.New(sha1.New, []byte(ossSercret))
	mac.Write([]byte(policy))

	return &v1.AliyunOssTokenMiniRes{
		OssJsCredential: &apiin.OssJsCredential{
			Policy:         policy,
			OSSAccessKeyId: ossAppKey,
			Signature:      base64.StdEncoding.EncodeToString(mac.Sum(nil)),
		},
	}, nil
}
